﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Dreamwork.Core.Infrastructure.RDSDb
{
	public abstract class RDSRepository<TEntity, TKey> : IRDSRepository<TEntity, TKey> where TEntity : DataModel<TKey>
	{
		private readonly DbContext _dbContext;
		private readonly ILogger<RDSRepository<TEntity, TKey>> _logger;
		public RDSRepository(DbContext dbContext, ILogger<RDSRepository<TEntity, TKey>> logger)
		{
			_dbContext = dbContext;
			_logger = logger;
		}
		protected abstract DbSet<TEntity> Entities { get; set; }

		public async Task AddAsync(TEntity item)
		{
			await Entities.AddAsync(item);
			await _dbContext.SaveChangesAsync();
		}

		public async Task<IEnumerable<TEntity>> GetAllAsync()
		{
			return await Entities.ToListAsync();
		}

		public async Task<TEntity> GetAsync(TKey id)
		{
			return await Entities.FirstOrDefaultAsync(x => Equals(x.Id, id));
		}

		public async Task<TEntity> GetAsync(Expression<Func<TEntity, bool>> selector)
		{
			return await Entities.FirstOrDefaultAsync(selector);
		}

		public async Task<IEnumerable<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> selector)
		{
			return await Entities.Where(selector).ToListAsync();
		}

		public async Task<bool> RemoveAllAsync()
		{
			var items = await Entities.ToListAsync();
			Entities.RemoveRange(items);
			await _dbContext.SaveChangesAsync();
			return true;
		}

		public async Task<bool> RemoveAsync(TKey id)
		{
			var item= await Entities.FirstOrDefaultAsync(x => Equals(x.Id, id));
			Entities.Remove(item);
			await _dbContext.SaveChangesAsync();
			return true;
		}

		public async Task<bool> UpdateAsync(TEntity model)
		{
			var item= await Entities.FirstOrDefaultAsync(x => Equals(x.Id, model.Id));
			 _dbContext.Update(item);
			await _dbContext.SaveChangesAsync();
			return true;
		}
	}
}
